//        var imgnum=0;
$(".mweb_modal_back_button").click(function(){
    history.go(-1);
});
var id;
if(/\?id=[0-9a-zA-Z]+/.test(location.href)){
    id=(location.href).match(/id=[0-9a-zA-Z]+/)[0].split("=")[1];
    $.cookie("MYID",id);
}else{
    id= $.cookie("MYID");
}
$("#gobackbtn").click(function(){
    history.go(-1);
});
//===============================================================================================================================================
//微信部分==========================================
var sendtohref=location.href.match(/qid=[0-9]+/)[0];
//alert($.cookie("qid"));
var qid=sendtohref.match(/[0-9]+/)[0];
$.ajax({
    type:"GET",
    url:"GetSign.ashx?p=weixin/answerpage.html?qid="+qid,
    //url:"GetSign.ashx?p=weixin/"+sendtohref,
    success:function(data){
        timestampone=data.timestamp;
        nonceStrone=data.nonceStr;
        signatureone=data.signature;
        wx.config({
            debug:false,
            appId: 'wx658c34793ecfd9f9',
            timestamp:timestampone, //时间戳
            nonceStr:nonceStrone,  //随机字符串
            signature:signatureone,  //SHA1编码
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                "chooseImage","uploadImage","previewImage","downloadImage"
            ]
        });
    }
});
//展示大图片------------------------------------------------
var winscrolltop;
var imghash={};//保存服务器返回的图片地址 “images.localId[i]”：imgurl
var delimgid="";//要删除的图片的Id
//展示大图
function showbigimg(e){
    winscrolltop=$(window).scrollTop();
    //console.log(winscrolltop);
    $("#page_wrapper").css("display","none");
    $("#showimg").attr("src", e.dataset.imgurl);//大图片的地址 和 Id 相同
    $("#digimgplace").css("display","block");
    var bigheight=$("#digimgplace").height();
    var imgheight=$("#showimg").height();
    if(bigheight>imgheight){
        $("#showimg").css("marginTop",(bigheight-imgheight)/2);
    }
    delimgid=e.dataset.img;//地址 和 Id 相同
}
//删除大图
$("#delthisimgbtn").click(function(e){
    imghash[delimgid]="";//清除对应ID 保存的服务器图片地址
    //页面中删掉图片
    var imgbox=document.getElementsByClassName("mainshowimgbox");
    for(var i= 0,r=imgbox.length;i<r;i++){
        if(imgbox[i].dataset.img==delimgid){
            //$imgbox=$(imgbox[i].dataset.img);
            $(".mainshowimgbox")[i].remove();
        }
    };
    $(".modifier.image").attr("class","modifier image toolbaricon");//还原class
    $(".modifier.image").css("display","inlineBlock");
    $("#page_wrapper").css("display","block");
    $("#digimgplace").css("display","none");
});
//关闭地图区域
$("#digimgplace").click(function(e){
    if(e.id!="delthisimgbtn"){
        $("#page_wrapper").css("display","block");
        $("#digimgplace").css("display","none");
        if(winscrolltop>0){
            //console.log(winscrolltop);
            $(window).scrollTop(winscrolltop);
        }
    }
});
//上传图片--------------------------------------------------
var images = {
    localId: [],
    serverId: []
};
var sendlocalIds;
var imgbtn=$(".modifier.image")[0];
imgbtn.onclick=function(){

    if(imgbtn.className==="modifier image toolbaricon"){
        //微信部分==========================================
        var imgnum=9;//选择图片个数
        if(document.getElementsByClassName("mainshowimgbox")&&document.getElementsByClassName("mainshowimgbox").length>0){
            imgnum=9-document.getElementsByClassName("mainshowimgbox").length;
        }
        wx.chooseImage({
            count: imgnum, // 默认9
            success: function(res) {
                var cameraimg;
                images.localId = res.localIds;
                //alert("本地ID："+res.localIds);
                //如果只选了一张照片 看成拍照设置cameraimg
                if( res.localIds.length==1){
                    cameraimg= res.localIds;
                    //alert("拍照的图片地址："+cameraimg);
                }
                //alert('已选择 ' + res.localIds.length + ' 张图片');
                if (images.localId.length == 0) {
                    alert('请先使用 chooseImage 接口选择图片');
                    return;
                }else{
                    //如果不是拍照
                    if(!cameraimg){
                        var divheight=parseFloat(window.innerWidth)*0.21;
                        for(var r=0;r<images.localId.length;r++){
                            //$("<div class='mainshowimgbox' style='height:"+divheight+"px;overflow:hidden;' onclick='showbigimg(this)' data-imgurl='"+images.localId[r]+"' data-img='"+images.localId[r]+"'><img src='"+images.localId[r]+"'></div>").insertBefore("#questionbody .modifier.image");
                            $("#questionbody").append("<div class='mainshowimgbox' style='height:"+divheight+"px;overflow:hidden;' onclick='showbigimg(this)' data-imgurl='"+images.localId[r]+"' data-img='"+images.localId[r]+"'><img src='"+images.localId[r]+"'></div>");
                        }
                    }
                }
                var divheight=parseFloat(window.innerWidth)*0.21;
                var i = 0, length = images.localId.length;
                images.serverId = [];
                function upload(){
                    wx.uploadImage({
                        localId: images.localId[i],
                        success: function(res) {
                            var locaimgurl=images.localId[i];
                            i++;
                            images.serverId.push(res.serverId);
                            //alert("发送的serverId："+res.serverId);
                            //请求服务器下载图片
                            $.ajax({
                                type:"get",
                                url:wxgetimgurl+res.serverId,
                                success:function(img){
                                    if(cameraimg&&cameraimg.length==1){ //只选了一张图片 看成拍照
                                        //$("<div class='mainshowimgbox' style='height:"+divheight+"px;overflow:hidden;' onclick='showbigimg(this)' data-imgurl='"+cameraimg+"' data-img='"+res.serverId+"'><img src='"+cameraimg+"'></div>").insertBefore("#questionbody .modifier.image");
                                        $("#questionbody").append("<div class='mainshowimgbox' style='height:"+divheight+"px;overflow:hidden;' onclick='showbigimg(this)' data-imgurl='"+cameraimg+"' data-img='"+res.serverId+"'><img src='"+cameraimg+"'></div>");
                                        imghash[res.serverId]=img.replace("C:\\","");
                                    }else{
                                        imghash[images.localId[i]]=img.replace("C:\\","");
                                    }
                                    //判断图片个数 9个隐藏按钮
                                    if(document.getElementsByClassName("mainshowimgbox")&&document.getElementsByClassName("mainshowimgbox").length==9){
                                        //$(".modifier.image").css("display","none");
                                        imgbtn.className="modifier image toolbaricon cannot";
                                    }
                                    //若果没上传好就继续
                                    if (i < length) {
                                        upload();
                                    }
                                }
                            });
                        },
                        fail: function(res) {
                            alert("图片上传失败，请稍后再次上传");
                            //alert(JSON.stringify(res));
                        }
                    });
                }
                upload();
            }
        });
    }
};
$("#addimgfilebtn").height(($(window).width()-30)*0.23);
//点击确定按钮发送回答----------------------------------------------------------------------------------------------
$("#okbtn").click(function(){
    $("#contentword").blur();
    var shareuser="";
    if(/shareUserId/.test(location.href)){
        shareuser=(location.href).match(/shareUserId=[0-9a-z]+/)[0].split("=")[1];
    }
    //点击进入
    if($.cookie("shareUserId")){
        shareuser=$.cookie("shareUserId");
    }
    //外部分享进入 级别最高 替换所有
    //if($.cookie("fromuser")){
    //    if($.cookie("fromuser")!=id){
    //        shareuser=$.cookie("fromuser");
    //    }
    //    //alert(shareuser);
    //}
    //alert(shareuser);
    if(document.getElementById("contentword").value&&!document.getElementById("contentword").value.match(/^\s+$/g)){
        var answer={};
        answer.questionId=qid;
        answer.answerUserId=id;
        answer.atype=2;  //评论新闻为2
        answer.replyto = "";
        answer.replytoNick = "";
        answer.content=document.getElementById("contentword").value;
        answer.shareUserId=shareuser;
        if(document.getElementById("hidenameinput").checked){
            answer.ishideName=1
        }else{
            answer.ishideName=0;
        }
        //图片
        var imgs=[];
        if(document.getElementsByClassName("mainshowimgbox")&&document.getElementsByClassName("mainshowimgbox").length>0){
            //从数组中获取图片
            var tim=0;
            var len=document.getElementsByClassName("mainshowimgbox").length;
            for(var key in imghash){
                tim++;
                if(imghash[key]){
                    var img={};
                    img=imghash[key];
                    imgs.push(img);
                }
                if(tim==len){
                    $("#sharewaiting").css("display","block");
                    $.ajax({
                        type:"post",
                        datatype:"json",
                        url:"https://www.pulu.com/webapi/api/PuluAnswer/AddAnswer_q",
                        data:{"puluanswer":answer,"imgs":imgs},
                        success:function(data){
                            if(data.Code==="TRUE"){
                                //alert("传递成功"+shareuser);
                                $.cookie("shareUserId","");
                                $.cookie("fromuser","");
                                //经验详情返回
                                if($.cookie("fromquestiondetial")&&$.cookie("fromquestiondetial").length>0){
                                    $.cookie("fromquestiondetial","");
                                    $("#questionbody .mainshowimgbox").remove();
                                    $("#contentword").val("");
                                    location.href="questiondetail.html?qid="+qid+"#fromuser="+id;
                                }else{
                                    $("#questionbody .mainshowimgbox").remove();
                                    $("#contentword").val("");
                                    history.go(-1);
                                }
                            }
                        }
                    })
                }
            }
        }else{
            $("#sharewaiting").css("display","block");
            $.ajax({
                type:"post",
                datatype:"json",
                url:"https://www.pulu.com/webapi/api/PuluAnswer/AddAnswer_q",
                data:{"puluanswer":answer,"imgs":imgs},
                success:function(data){
                    if(data.Code==="TRUE"){
                        //alert("传递成功"+shareuser);
                        $.cookie("shareUserId","");
                        $.cookie("fromuser","");
                        //经验详情返回
                        if($.cookie("fromquestiondetial")&&$.cookie("fromquestiondetial").length>0){
                            $.cookie("fromquestiondetial","");
                            $("#questionbody .mainshowimgbox").remove();
                            $("#contentword").val("");
                            location.href="questiondetail.html?qid="+qid+"#fromuser="+id;
                        }else{
                            $("#questionbody .mainshowimgbox").remove();
                            $("#contentword").val("");
                            history.go(-1);
                        }
                    }
                }
            })
        }
    }
    else{
        alert("回答内容不能为空");
    }
});